package org.jetnuke.modules.weblinks;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.LinkLinkDAO;

public class Top implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Top.class);

	int ratenum = 25;
	int linkvotemin = 5;// TODO
	String ratetype = "num";

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		int toplinkspercentrigger = 0;
		int toplinks = ratenum;
		int toplinkspercent = toplinks;
		if (ratetype.equals("percent")) {
			toplinkspercentrigger = 1;
		}
		LinkLinkDAO llm = DataAccessDriver.getInst().newLinkLinkDAO();
		if (toplinkspercentrigger == 1) {

			int totalratedlinks = llm.countWithRating();// links_linksPeer.count(new
														// Criteria().add(links_linksPeer.LINKRATINGSUMMARY,0d,Criteria.GREATER_THAN));
			toplinks = (int) (1. * totalratedlinks * toplinks / 100);
			vc.put("totalratedlinks", new Integer(totalratedlinks));
		}
		vc.put("toplinkspercentrigger", new Integer(toplinkspercentrigger));
		vc.put("toplinks", new Integer(toplinks));
		vc.put("linkvotemin", new Integer(linkvotemin));
		vc.put("toplinkspercent", new Integer(toplinkspercent));

		vc.put("links", llm.selectWithRating(linkvotemin, toplinks));// links_linksPeer.doSelect(new
																		// Criteria().add(links_linksPeer.LINKRATINGSUMMARY,0d,Criteria.GREATER_THAN).add(links_linksPeer.TOTALVOTES,linkvotemin,Criteria.GREATER_EQUAL).addDescendingOrderByColumn(links_linksPeer.LINKRATINGSUMMARY).setLimit(toplinks)));

		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

	public void setRatenum(int rateNum) {
		this.ratenum = rateNum;
	}

	public void setRatetype(String ratetype) {
		this.ratetype = ratetype;
	}
}
